//
//  AllCourseDetail.swift
//  ddx0513
//
//  Created by jiang yongbin on 15/6/1.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit


class AllCourseDetail: UIViewController, DeliverSectionidDelegate, UIAlertViewDelegate, DownloadDelegate {
    var videoPlayer: PLVMoviePlayerController?
    var vid = ""
    var progress = 0
    var isPosterImageview = false
    var posterImageView: UIImageView?
    var posterImageUrl = ""
    var indicatorView: UIActivityIndicatorView?
    var lessonId:Int?
    var controlView: UIView?
    var playButton1: UIButton?
    var fullScreenButton1: UIButton?
    let playImg1 = UIImage(named: "播放2.png")
    let stopImg1 = UIImage(named: "暂停2.png")
    var slider1: UISlider?
    var progressView: UIProgressView?
    var nowTimeLabel1: UILabel?
    var allTimeLabel1: UILabel?
    var playStatus = false
    var controlViewDisplay = true
    var controlViewShouldDisplay = false
    var allPlayTime = 0
    var backButton1: UIButton?
    var titleLabel1: UILabel?
    var backView: UIView?
    var backView1: UIView?
    var backView2: UIView?
    var nowTimer: NSTimer?
    var barTimer: NSTimer?
    var barTime = 0
    var shouldSetProgress = false
    var isFullScreen = false
    var controllerViewHeight = 38 as CGFloat
    var fullScreenImgSmall: UIImage?
    var sliderDragging = false
    var reachability: Reachability?
    var netStatus: Reachability.NetworkStatus?
    let nowTimeWidthSmall = 32 as CGFloat
    let nowTimeWidthLarge = 42 as CGFloat
    let allTimeWidthSmall = 36 as CGFloat
    let allTimeWidthLarge = 46 as CGFloat
    var sectionId = 0
    var lessonName = ""
    var isPlaybackFinished = false
    var allowCellular = false
    var download: VideoDownloader?
    var isDownloading = false
    var isFirstPage = true
    var containerSelected: UIViewController?
    var isFree = 0

    
    @IBOutlet weak var lineViewTopConstraint: NSLayoutConstraint!
    @IBOutlet weak var detailBtn: UIButton!
  //  var lessonId:NSMutableArray = []
    
    @IBOutlet weak var lineView: UIImageView!
   @IBOutlet var navTitle:UINavigationItem!
    @IBOutlet weak var SubContainer: UIView!
        @IBOutlet var name : UILabel!
    var detailItem: NSString?
     //var  subMenu:CCSegmentedControl! = nil
    //var learning:LearningViewController! = nil
    var detailArr = NSMutableArray()
    //var LearningCourse:LearningTVController! = nil
    var LearningCourse:LearningViewController! = nil
    var allcourse:AllCourseViewController! = nil
    var JudgeCourse:CourseJudgeViewController! = nil
  //  var MessageCourse:CourseMessageTVController! = nil
    var MessageCourse:CourseMessageViewController! = nil
    
    // MARK: - 视图
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.userInteractionEnabled = true
        rootController.navigationController?.setNavigationBarHidden(true, animated: false)
        
        //加载播放器
        //自动选择码率
        self.videoPlayer = PLVMoviePlayerController()
//        self.download = VideoDownloader()
//        self.download?.setDownloadDelegate(self)
//        self.download?.addSkipBackupAttributeToDownloadedVideos()
        var view = UIView()
        view.backgroundColor = UIColor.blackColor()
        self.view.addSubview(view)
        self.view.addSubview(self.videoPlayer!.view)
        
        var frame = self.view.frame
        var w = frame.size.width
        var h = frame.size.height
        let h1 = w / 16 * 9
        let h2 = h1 + getTopHeight()
        
        self.videoPlayer?.view.frame = CGRectMake(0, getTopHeight(), self.view.frame.size.width, h1)
        view.frame = self.videoPlayer!.view.frame
        self.videoPlayer?.controlStyle = MPMovieControlStyle.None
        self.videoPlayer?.scalingMode = MPMovieScalingMode.Fill
        
        var size = self.videoPlayer!.view.frame.size
        indicatorView = UIActivityIndicatorView(frame: CGRectMake(size.width / 2 - 10, size.height / 2 + getTopHeight() - 10, 20, 20))
        indicatorView?.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.White
        self.view.addSubview(indicatorView!)
        
        initViews()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerLoadStateDidChange:"), name: MPMoviePlayerLoadStateDidChangeNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playbackStateDidChange:"), name: MPMoviePlayerPlaybackStateDidChangeNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerPlayBackDidFinish:"), name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerReadyForDisplayDidChange:"), name: MPMoviePlayerReadyForDisplayDidChangeNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("applicationWillResignActive:"), name: UIApplicationWillResignActiveNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("applicationDidBecomeActive:"), name: UIApplicationDidBecomeActiveNotification, object: nil)
        
        
        //网络检测
        self.reachability = Reachability.reachabilityForInternetConnection()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
        reachability!.startNotifier()
        self.netStatus = self.reachability?.currentReachabilityStatus
        
        var playView = CCSegmentedControl(items: ["课程目录","课程信息","课程评价"])
        playView.frame=CGRectMake(0, h2, UIScreen.mainScreen().bounds.size.width, 40)
        var selectedItem: UIView = playView.items[playView.selectedSegmentIndex] as! UIView;
        playView.selectedStainView.frame = CGRectMake(28.75,40,80,1)
        playView.selectedStainView = UIImageView(image: UIImage(named: "选中.png"))
        playView.backgroundColor = playView.colorWithHexString("#ffffff")
        playView.selectedSegmentTextColor = playView.colorWithHexString("#0cac69")
        playView.segmentTextColor = playView.colorWithHexString("#646464")      
        playView.addTarget(self, action: Selector("playMenuvalueChanged:"), forControlEvents: UIControlEvents.ValueChanged )
        self.view.addSubview(playView)
        
        var lineViewFrame = self.lineView.frame
        let lineViewY = h2 + playView.frame.size.height
        self.lineViewTopConstraint.constant = lineViewY
        
        LearningCourse = UIStoryboard(name: "Learning", bundle: nil).instantiateViewControllerWithIdentifier("Learning") as! LearningViewController
        LearningCourse.lessonId = lessonId
        LearningCourse.view.frame = CGRect(x: 0, y: 0, width: SubContainer.frame.width, height: SubContainer.frame.height)
        LearningCourse.delegate = self
        
        self.addChildViewController(LearningCourse)
        SubContainer.addSubview(LearningCourse.view)
        LearningCourse.didMoveToParentViewController(self)
        self.containerSelected = LearningCourse
//        SubContainer.bringSubviewToFront(LearningCourse.view)
        

        //end 加载
   
////////////////////////////////

        // Do any additional setup after loading the view.
    }
    
    override func viewDidDisappear(animated: Bool) {
        self.videoPlayer?.pause()
        syncProgress()
        self.videoPlayer?.stop()
//        self.download?.stop()
//        self.isDownloading = false
        self.videoPlayer = nil
        self.nowTimer?.invalidate()
        self.nowTimer = nil
        self.barTimer?.invalidate()
        self.barTimer = nil
        self.barTime = 0
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerLoadStateDidChangeNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackStateDidChangeNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerReadyForDisplayDidChangeNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
        self.reachability?.stopNotifier()
        NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: reachability)
        
        
//        var dic = NSBundle.mainBundle().infoDictionary as! [String : AnyObject]
//        dic["UISupportedInterfaceOrientations"] = ["UIInterfaceOrientationPortrait"]
    }
    
    
    func playMenuvalueChanged(sender:CCSegmentedControl)
    {
        
        var subMenu:CCSegmentedControl = sender
        var selectedItem: UIView = subMenu.items[subMenu.selectedSegmentIndex] as! UIView;
        subMenu.selectedStainView.frame = CGRectMake(selectedItem.frame.origin.x-10,40,selectedItem.frame.size.width+20,1);
        if(subMenu.selectedSegmentIndex == 0 && self.containerSelected != LearningCourse)
        {
            if (subMenu.selectedSegmentIndex == 1 && self.containerSelected != LearningCourse) {
                LearningCourse = UIStoryboard(name: "Learning", bundle: nil).instantiateViewControllerWithIdentifier("Learning") as! LearningViewController
                LearningCourse.lessonId = lessonId
                LearningCourse.view.frame = CGRect(x: 0, y: 0, width: SubContainer.frame.width, height: SubContainer.frame.height)
                LearningCourse.delegate = self
                //                SubContainer.addSubview(LearningCourse.view)
                self.addChildViewController(LearningCourse)
//                SubContainer.addSubview(LearningCourse.view)
                LearningCourse.didMoveToParentViewController(self)
            }
            
            transitionFromViewController(self.containerSelected!, toViewController: LearningCourse, duration: 0, options: nil, animations: nil, completion: nil)
            self.containerSelected = LearningCourse
            
            
            self.detailBtn.titleLabel?.text = "开始学习"

        }
        else if(subMenu.selectedSegmentIndex == 1 && self.containerSelected != MessageCourse)
        {
            if (MessageCourse == nil) {
                MessageCourse = UIStoryboard(name: "CourseMessage", bundle: nil).instantiateViewControllerWithIdentifier("CourseMessage") as! CourseMessageViewController
                MessageCourse.lessonId = lessonId
                MessageCourse.view.frame = CGRect(x: 0, y: 0, width: SubContainer.frame.width, height: SubContainer.frame.height)
                
                
                self.addChildViewController(MessageCourse)
                MessageCourse.didMoveToParentViewController(self)
            }
            transitionFromViewController(self.containerSelected!, toViewController: MessageCourse, duration: 0, options: nil, animations: nil, completion: nil)
            self.containerSelected = MessageCourse
            self.detailBtn.titleLabel?.text = "开始学习"

        }
        else if(subMenu.selectedSegmentIndex == 2 && self.containerSelected != JudgeCourse)
        {
            if (JudgeCourse == nil) {
                JudgeCourse = UIStoryboard(name: "CourseJudge", bundle: nil).instantiateViewControllerWithIdentifier("coursejudge") as! CourseJudgeViewController
                JudgeCourse.lessonId = lessonId
                
                JudgeCourse.view.frame = CGRect(x: 0, y: 0, width: SubContainer.frame.width, height: SubContainer.frame.height)
                
                self.addChildViewController(JudgeCourse)
                JudgeCourse.didMoveToParentViewController(self)
            }
            transitionFromViewController(self.containerSelected!, toViewController: JudgeCourse, duration: 0, options: nil, animations: nil, completion: nil)
            self.containerSelected = JudgeCourse
            
            self.detailBtn.titleLabel?.text = "开始学习"

            
        }

        
    }
    
    func getTopHeight() -> CGFloat {
        var statusHeight = UIApplication.sharedApplication().statusBarFrame.height
//        var barHeight = 0 as CGFloat
//        if (!self.navigationController!.navigationBarHidden) {
//            if let a = self.navigationController?.navigationBar.frame.size.height {
//                barHeight = a
//            }
//        }
//        var topHeight = statusHeight + barHeight
        
        return statusHeight
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func goBack(sender: AnyObject) {
        if (!self.isFullScreen) {
            self.navigationController?.popViewControllerAnimated(true)
            rootController.navigationController?.setNavigationBarHidden(true, animated: true)
        } else {
            self.fullScreenButtonTapped()
        }
    //modify by py 如果不是首页，不隐藏导航栏
    if(!isFirstPage)
    {
        rootController.navigationController?.setNavigationBarHidden(false, animated: true)
    }
}
    // MARK: - 视频播放
    
    func initViews() {
        var size = self.videoPlayer!.view.frame.size
        
        //首帧图片
        self.posterImageView = UIImageView(frame: CGRectMake(0, 0, self.videoPlayer!.view.frame.size.width, self.videoPlayer!.view.frame.size.height))
        self.posterImageView!.userInteractionEnabled = true
        var videoTap = UITapGestureRecognizer(target: self, action: Selector("videoAreaTapped"))
        self.posterImageView!.addGestureRecognizer(videoTap)
        
        self.videoPlayer!.view.addSubview(self.posterImageView!)
        
        /********************上方标题图层****************************/
        //标题图层
        self.backView = UIView(frame: CGRectMake(0, 0, size.width, self.controllerViewHeight))
        self.videoPlayer!.view.addSubview(self.backView!)
        
        //黑色背景图层
        self.backView1 = UIView(frame: CGRectMake(0, 0, self.backView!.frame.size.width, self.backView!.frame.size.height))
        self.backView1!.backgroundColor = UIColor.blackColor()
        self.backView1!.alpha = 0.5
        self.backView?.addSubview(self.backView1!)
        
        self.backButton1 = UIButton(frame: CGRectMake(5, 0, controllerViewHeight, controllerViewHeight))
        self.backButton1?.setImage(UIImage(named: "返回_2.png"), forState: UIControlState.Normal)
        self.backButton1?.addTarget(self, action: Selector("goBack:"), forControlEvents: UIControlEvents.TouchUpInside)
        self.backView?.addSubview(self.backButton1!)
        
        self.titleLabel1 = UILabel(frame: CGRectMake(41, 0, self.backView!.frame.size.width - 41, self.backView!.frame.size.height))
        self.titleLabel1?.textColor = UIColor.whiteColor()
        let font1 = UIFont.systemFontOfSize(16 as CGFloat)
        self.titleLabel1?.font = font1
        self.titleLabel1?.text = self.lessonName
        self.titleLabel1?.adjustsFontSizeToFitWidth = true
        self.backView?.addSubview(self.titleLabel1!)
        
        /*****************下方控制条图层**************************/
        //控制条图层
        self.controlView = UIView(frame: CGRectMake(0, size.height - self.controllerViewHeight, size.width, self.controllerViewHeight))
        self.videoPlayer!.view.insertSubview(self.controlView!, belowSubview: self.backView!)
        
        //黑色背景图层
        self.backView2 = UIView(frame: CGRectMake(0, 0, self.controlView!.frame.size.width, self.controlView!.frame.size.height))
        self.backView2!.backgroundColor = UIColor.blackColor()
        self.backView2!.alpha = 0.5
        self.controlView?.addSubview(self.backView2!)
        
        //播放按钮
        var playButtonY = (self.controllerViewHeight - self.playImg1!.size.height) / 2
        self.playButton1 = UIButton(frame: CGRectMake(10, playButtonY, self.playImg1!.size.width, self.playImg1!.size.height))
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Normal)
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Highlighted)
        self.playButton1?.addTarget(self, action: Selector("playButtonTapped"), forControlEvents: UIControlEvents.TouchUpInside)
        self.playButton1?.addTarget(self, action: Selector("playButtonTouchDown"), forControlEvents: UIControlEvents.TouchDown)
        self.playButton1?.userInteractionEnabled = false
        self.controlView!.addSubview(self.playButton1!)
        
        //全屏按钮
        self.fullScreenImgSmall = UIImage(named: "放大.png")
        var fullScreenButtonY = (self.controllerViewHeight - fullScreenImgSmall!.size.height) / 2
        self.fullScreenButton1 = UIButton(frame: CGRectMake(self.controlView!.frame.size.width - 5 - fullScreenImgSmall!.size.width, fullScreenButtonY, fullScreenImgSmall!.size.width, fullScreenImgSmall!.size.height))
        self.fullScreenButton1?.setBackgroundImage(fullScreenImgSmall, forState: UIControlState.Normal)
        self.fullScreenButton1?.addTarget(self, action: Selector("fullScreenButtonTapped"), forControlEvents: UIControlEvents.TouchUpInside)
        self.fullScreenButton1?.addTarget(self, action: Selector("fullScreenButtonTouchDown"), forControlEvents: UIControlEvents.TouchDown)
        self.fullScreenButton1?.userInteractionEnabled = false
        self.controlView!.addSubview(self.fullScreenButton1!)
        
        //时间标签
        let font = UIFont.systemFontOfSize(12 as CGFloat)
        self.allTimeLabel1 = UILabel(frame: CGRectMake(self.fullScreenButton1!.frame.origin.x - allTimeWidthSmall, self.controlView!.frame.size.height / 3, allTimeWidthSmall, self.controlView!.frame.size.height / 3))
        self.allTimeLabel1?.font = font
        self.allTimeLabel1?.textColor = UIColor.whiteColor()
        self.allTimeLabel1?.text = "/00:00"
        self.controlView!.addSubview(self.allTimeLabel1!)
        
        self.nowTimeLabel1 = UILabel(frame: CGRectMake(self.allTimeLabel1!.frame.origin.x - nowTimeWidthSmall, self.allTimeLabel1!.frame.origin.y, nowTimeWidthSmall, self.allTimeLabel1!.frame.size.height))
        self.nowTimeLabel1?.font = font
        self.nowTimeLabel1?.textColor = UIColor.whiteColor()
        self.nowTimeLabel1?.textAlignment = NSTextAlignment.Right
        self.nowTimeLabel1?.text = "00:00"
        self.controlView!.addSubview(self.nowTimeLabel1!)
        
        self.slider1 = UISlider(frame: CGRectMake(self.playButton1!.frame.origin.x + self.playImg1!.size.width + 10, self.controlView!.frame.size.height / 4, self.nowTimeLabel1!.frame.origin.x - 3 - self.playButton1!.frame.origin.x - self.playImg1!.size.width - 10, self.controlView!.frame.size.height / 2 + 1))
        let thumbImage = UIImage(named: "教程全屏_03.png")
        self.slider1?.setThumbImage(thumbImage, forState: UIControlState.Normal)
        self.slider1?.setThumbImage(thumbImage, forState: UIControlState.Highlighted)
        self.slider1?.minimumTrackTintColor = UIColor.redColor()
        self.slider1?.maximumTrackTintColor = UIColor.clearColor()
        self.slider1?.minimumValue = 0
        self.slider1?.addTarget(self, action: Selector("slider1TouchUpInside"), forControlEvents: UIControlEvents.TouchUpInside)
        self.slider1?.addTarget(self, action: Selector("slider1TouchDown"), forControlEvents: UIControlEvents.TouchDown)
        self.slider1?.addTarget(self, action: Selector("slider1ChangedValue"), forControlEvents: UIControlEvents.ValueChanged)
        self.controlView!.addSubview(self.slider1!)
        
        var sliderBounds = self.slider1?.bounds
        self.progressView = UIProgressView(frame: CGRectMake(2, sliderBounds!.height / 2 - 1, sliderBounds!.width - 4, sliderBounds!.height))
        self.progressView?.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
        self.progressView?.userInteractionEnabled = false
        self.progressView?.progressTintColor = UIColor.lightGrayColor()
        self.progressView?.trackTintColor = UIColor.blackColor()
        self.slider1!.addSubview(self.progressView!)
        self.slider1!.sendSubviewToBack(self.progressView!)
        self.slider1?.hidden = true
        
        
        self.controlViewShouldDisplay = false
        self.controlView?.hidden = true
        self.controlViewDisplay = false
    }
    
    func initVideo() {
        self.videoPlayer?.stop()
//        self.download?.stop()
//        self.isDownloading = false
        self.nowTimer?.invalidate()
        self.nowTimer = nil
        self.barTimer?.invalidate()
        self.barTimer = nil
        self.barTime = 0
        self.playStatus = false
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Normal)
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Highlighted)
        self.indicatorView?.stopAnimating()
        self.playButton1?.userInteractionEnabled = false
        self.fullScreenButton1?.userInteractionEnabled = false
        self.nowTimeLabel1?.text = "00:00"
        self.allTimeLabel1?.text = "/00:00"
        self.slider1?.setValue(0, animated: false)
        self.progressView?.progress = 0
        self.isPlaybackFinished = false
        self.slider1?.hidden = true
        
        if (self.isPosterImageview) {
            self.posterImageView?.image = nil
            self.isPosterImageview = false
        }
        
        self.controlViewShouldDisplay = false
        self.controlView?.hidden = true
        self.controlViewDisplay = false
        
        if (vid != "") {
            NetPolyv.getVideoInfoById(vid, successHandler: getVideoById)
        }
    }
    
    //当前播放时间
    func nowTimeFireMethod() -> Void {
        if (self.playStatus && self.videoPlayer != nil && !isnan(self.videoPlayer!.currentPlaybackTime) && !isinf(self.videoPlayer!.currentPlaybackTime)) {
            let time = Int(self.videoPlayer!.currentPlaybackTime)
            let playableTime = Float(self.videoPlayer!.playableDuration)
            if (!self.sliderDragging) {
                self.slider1?.setValue(Float(time), animated: true)
                self.progressView?.setProgress(playableTime / Float(self.allPlayTime), animated: true)
                self.nowTimeLabel1?.text = StringUtils.getFormatPlayTime(time)
            }
        }
    }
    
    //控制条出现时间
    func barTimeFireMethod() {
        barTime++
        if (barTime >= 5) {
            barTimer?.invalidate()
            barTimer = nil
            barTime = 0
            
            if (self.controlViewDisplay) {
                self.controlViewDisplay = false
                self.controlView?.hidden = true
                if (self.isFullScreen) {
                    self.backView?.hidden = true
                }
            }
        }
    }
    
    //获取单个视频信息
    func getVideoById(json: JSON) {
        self.isPosterImageview = true
        
        if let a = json[0]["duration"].string {
            self.allPlayTime = StringUtils.getSeconds(a)
        }
        self.videoPlayer?.setVid(self.vid)
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
            if (self.netStatus == Reachability.NetworkStatus.ReachableViaWiFi && self.videoPlayer != nil) {
                    self.videoPlayer!.prepareToPlay()
            }
        })
        
        self.reSetControlView()
        
        self.controlViewShouldDisplay = true
        self.controlView?.hidden = false
        self.controlViewDisplay = true
        
        self.allTimeLabel1?.text = "/" + StringUtils.getFormatPlayTime(self.allPlayTime)
        self.nowTimeLabel1?.text = "00:00"
        self.nowTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("nowTimeFireMethod"), userInfo: nil, repeats: true)
        self.playButton1?.userInteractionEnabled = true
        self.fullScreenButton1?.userInteractionEnabled = true
        self.slider1?.maximumValue = Float(self.allPlayTime)
        
        self.videoPlayer?.shouldAutoplay = false
        
        if let a = json[0]["first_image"].string {
            self.posterImageUrl = a
            DBUtils.getImageFromFile(self.posterImageUrl, successHandler: setFirstImage)
        }
        
    }
    
    func setFirstImage(url: String, image: UIImage) {
        if (url == self.posterImageUrl && self.isPosterImageview) {
            self.posterImageView?.image = image
        }
    }
    
    func slider1ChangedValue() {
        let value = self.slider1?.value
        self.nowTimeLabel1?.text = StringUtils.getFormatPlayTime(Int(value!))
    }
    
    func slider1TouchDown() {
        self.sliderDragging = true
        self.invalideBarTimer()
    }
    
    func slider1TouchUpInside() {
        let value = self.slider1?.value
        self.videoPlayer?.currentPlaybackTime = Double(value!)
        self.nowTimeLabel1?.text = StringUtils.getFormatPlayTime(Int(value!))
        self.play()
        self.sliderDragging = false
        
        self.initBarTimer()
    }
    
    func popPlayCheckView() {
        var device : UIDevice = UIDevice.currentDevice()
        var systemVersion = device.systemVersion
        var iosVerion = (systemVersion as NSString).floatValue
        if(iosVerion < 8.0) {
            let alert = UIAlertView(title: "", message: "您现在使用的是运营商网络，继续观看可能产生超额流量费用。", delegate: self, cancelButtonTitle: "取消观看", otherButtonTitles: "继续观看")
            alert.show()
        } else {
            var alert : UIAlertController = UIAlertController(title: "", message: "您现在使用的是运营商网络，继续观看可能产生超额流量费用。", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "继续观看", style: .Default, handler: { (action: UIAlertAction!) -> Void in                
                self.allowCellular = true
                self.play()
            }))
            alert.addAction(UIAlertAction(title: "取消观看", style:.Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        switch (buttonIndex) {
        case 0:
            return
        case 1:
            self.allowCellular = true
            self.play()
        default:
            return
        }
    }
    
    func playButtonTouchDown() {
        self.invalideBarTimer()
    }
    
    func playButtonTapped() {
        self.initBarTimer()
        
        if (self.playStatus) {
            self.pause()
        } else {
            if (self.isPosterImageview && !DBUtils.mem.isCellularNet && !self.allowCellular && self.netStatus == Reachability.NetworkStatus.ReachableViaWWAN) {
//            if (self.isPosterImageview && !DBUtils.mem.isCellularNet && !self.allowCellular) {
                popPlayCheckView()
            } else {
                self.play()
            }
        }
    }
    
    func pause() {
        self.playStatus = false
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Normal)
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Highlighted)
        self.indicatorView?.stopAnimating()
        self.videoPlayer!.pause()
    }
    
    func play() {
        if (!self.playStatus) {
            self.playStatus = true
            self.playButton1?.setBackgroundImage(self.stopImg1, forState: UIControlState.Normal)
            self.playButton1?.setBackgroundImage(self.stopImg1, forState: UIControlState.Highlighted)
        }
    
        if (self.isPosterImageview) {
            self.slider1?.hidden = false
            self.posterImageView?.image = nil
            self.isPosterImageview = false
//            self.indicatorView?.startAnimating()
            self.shouldSetProgress = true
            
            if (self.playStatus) {
                self.barTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("barTimeFireMethod"), userInfo: nil, repeats: true)
                self.barTime = 0
            }
        }
        
        self.videoPlayer!.play()
        
        
    }
    
    func fullScreenButtonTouchDown() {
        self.invalideBarTimer()
    }
    
    func fullScreenButtonTapped() {
        if (isFullScreen) {
            self.initBarTimer()
//            DBUtils.mem.isFullScreen = false
            self.isFullScreen = false
            setNormalScreen()
            
        } else {
//            DBUtils.mem.isFullScreen = true
            self.isFullScreen = true
            setFullScreen()
            
            if (self.isPosterImageview && !DBUtils.mem.isCellularNet && !self.allowCellular && self.netStatus == Reachability.NetworkStatus.ReachableViaWWAN) {
                popPlayCheckView()
            } else {
                self.initBarTimer()
                self.play()
            }
            
        }
        
    }
    
    func setNormalScreen() {
//        OcUtils.rotateScreenToPortrait()
//        UIDevice.currentDevice().setValue(NSNumber(integer: UIInterfaceOrientation.LandscapeRight.rawValue), forKey: "orientation")
        UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
        
        var duration = UIApplication.sharedApplication().statusBarOrientationAnimationDuration
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(duration)
        
        
        self.videoPlayer!.view.transform = CGAffineTransformIdentity
        self.videoPlayer!.view.transform = CGAffineTransformMakeRotation(CGFloat(0))
        var frame = self.view.frame
        var w = frame.size.width
        var h = frame.size.height
        var h2 = w / 16 * 9
        self.videoPlayer!.view.frame = CGRectMake(0, getTopHeight(), self.view.frame.size.width, h2)
        self.view.bringSubviewToFront(self.videoPlayer!.view)
        
        var size = self.videoPlayer!.view.frame.size
        self.posterImageView?.frame = CGRectMake(0, 0, size.width, size.height)
        self.indicatorView?.frame = CGRectMake(size.width / 2 - 10, size.height / 2 + getTopHeight() - 10, 20, 20)
        self.backView?.frame = CGRectMake(0, 0, size.width, self.controllerViewHeight)
        self.backView1?.frame = CGRectMake(0, 0, size.width, self.controllerViewHeight)
        self.titleLabel1?.frame = CGRectMake(41, 0, size.width - 41, self.backView!.frame.size.height)
        
        self.controlView?.frame = CGRectMake(0, size.height - self.controllerViewHeight, size.width, self.controllerViewHeight)
        self.backView2?.frame = CGRectMake(0, 0, size.width, self.controllerViewHeight)
        
        self.reSetControlView()
        
        UIView.commitAnimations()
    }
    
    func setFullScreen() {
//        OcUtils.rotateScreenToLandscapeRight()
//        UIDevice.currentDevice().setValue(NSNumber(integer: UIDeviceOrientation.Portrait.rawValue), forKey: "orientation")
//        UIDevice.currentDevice().setValue(NSNumber(integer: UIDeviceOrientation.LandscapeRight.rawValue), forKey: "orientation")
        UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade)
        
        var duration = UIApplication.sharedApplication().statusBarOrientationAnimationDuration
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(duration)
        
        self.videoPlayer!.view.transform = CGAffineTransformIdentity
        self.videoPlayer!.view.transform = CGAffineTransformMakeRotation(CGFloat(M_PI/2))

        var frame = self.view.frame
        var w = frame.size.width
        var h = frame.size.height
        self.videoPlayer!.view.frame = CGRectMake(0, 0, w, h)
        self.view.bringSubviewToFront(self.videoPlayer!.view)
        
        self.posterImageView?.frame = CGRectMake(0, 0, h, w)
        
        self.indicatorView?.frame = CGRectMake(h / 2 - 10, w / 2 - 10, 20, 20)
        
        self.backView?.frame = CGRectMake(0, 0, h, self.controllerViewHeight)
        self.backView1?.frame = CGRectMake(0, 0, h, self.controllerViewHeight)
        self.titleLabel1?.frame = CGRectMake(41, 0, h - 41, self.backView!.frame.size.height)
        
        self.controlView?.frame = CGRectMake(0, w - self.controllerViewHeight, h, self.controllerViewHeight)
        self.backView2?.frame = CGRectMake(0, 0, h, self.controllerViewHeight)
        
        self.reSetControlView()

        UIView.commitAnimations()
    }
    
    func reSetControlView() {
        if (self.isFullScreen) {
            var fullScreenButtonY = (self.controllerViewHeight - fullScreenImgSmall!.size.height) / 2
            self.fullScreenButton1?.frame = CGRectMake(self.controlView!.frame.size.width - 10 - fullScreenImgSmall!.size.width, fullScreenButtonY, fullScreenImgSmall!.size.width, fullScreenImgSmall!.size.height)
            self.fullScreenButton1?.setBackgroundImage(UIImage(named: "缩小2.png"), forState: UIControlState.Normal)
            
            if (self.allPlayTime >= 3600) {
                self.allTimeLabel1?.frame = CGRectMake(self.fullScreenButton1!.frame.origin.x - allTimeWidthLarge, self.controlView!.frame.size.height / 3, allTimeWidthLarge, self.controlView!.frame.size.height / 3)
                self.nowTimeLabel1?.frame = CGRectMake(self.allTimeLabel1!.frame.origin.x - nowTimeWidthLarge, self.allTimeLabel1!.frame.origin.y, nowTimeWidthLarge, self.allTimeLabel1!.frame.size.height)
            } else {
                self.allTimeLabel1?.frame = CGRectMake(self.fullScreenButton1!.frame.origin.x - allTimeWidthSmall, self.controlView!.frame.size.height / 3, allTimeWidthSmall, self.controlView!.frame.size.height / 3)
                self.nowTimeLabel1?.frame = CGRectMake(self.allTimeLabel1!.frame.origin.x - nowTimeWidthSmall, self.allTimeLabel1!.frame.origin.y, nowTimeWidthSmall, self.allTimeLabel1!.frame.size.height)
            }
            
            self.slider1?.frame = CGRectMake(self.playButton1!.frame.origin.x + self.playImg1!.size.width + 15, self.controlView!.frame.size.height / 4, self.nowTimeLabel1!.frame.origin.x - 5 - self.playButton1!.frame.origin.x - self.playImg1!.size.width - 15, self.controlView!.frame.size.height / 2 + 1)
        } else {
            var fullScreenButtonY = (self.controllerViewHeight - fullScreenImgSmall!.size.height) / 2
            self.fullScreenButton1?.frame = CGRectMake(self.controlView!.frame.size.width - 5 - fullScreenImgSmall!.size.width, fullScreenButtonY, fullScreenImgSmall!.size.width, fullScreenImgSmall!.size.height)
            self.fullScreenButton1?.setBackgroundImage(UIImage(named: "放大.png"), forState: UIControlState.Normal)
            
            if (self.allPlayTime >= 3600) {
                self.allTimeLabel1?.frame = CGRectMake(self.fullScreenButton1!.frame.origin.x - allTimeWidthLarge, self.controlView!.frame.size.height / 3, allTimeWidthLarge, self.controlView!.frame.size.height / 3)
                self.nowTimeLabel1?.frame = CGRectMake(self.allTimeLabel1!.frame.origin.x - nowTimeWidthLarge, self.allTimeLabel1!.frame.origin.y, nowTimeWidthLarge, self.allTimeLabel1!.frame.size.height)
            } else {
                self.allTimeLabel1?.frame = CGRectMake(self.fullScreenButton1!.frame.origin.x - allTimeWidthSmall, self.controlView!.frame.size.height / 3, allTimeWidthSmall, self.controlView!.frame.size.height / 3)
                self.nowTimeLabel1?.frame = CGRectMake(self.allTimeLabel1!.frame.origin.x - nowTimeWidthSmall, self.allTimeLabel1!.frame.origin.y, nowTimeWidthSmall, self.allTimeLabel1!.frame.size.height)
            }
            
            self.slider1?.frame = CGRectMake(self.playButton1!.frame.origin.x + self.playImg1!.size.width + 10, self.controlView!.frame.size.height / 4, self.nowTimeLabel1!.frame.origin.x - 3 - self.playButton1!.frame.origin.x - self.playImg1!.size.width - 10, self.controlView!.frame.size.height / 2 + 1)
        }
        
    }
    
    func invalideBarTimer() {
        if (barTimer != nil && barTimer!.valid) {
            barTimer?.invalidate()
            barTimer = nil
            barTime = 0
        }
    }
    
    func initBarTimer() {
        if (self.playStatus) {
            self.barTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("barTimeFireMethod"), userInfo: nil, repeats: true)
            self.barTime = 0
        }
    }
    
    func videoAreaTapped() {
        if (controlViewShouldDisplay) {
            if (self.controlViewDisplay) {
                self.controlViewDisplay = false
                self.controlView?.hidden = true
                if (self.isFullScreen) {
                    self.backView?.hidden = true
                }
                
                self.invalideBarTimer()
            } else {
                self.controlViewDisplay = true
                self.controlView?.hidden = false
                if (self.isFullScreen) {
                    self.backView?.hidden = false
                }
                
                self.initBarTimer()
            }
        }
    }
    
    func syncProgress(lessonId: Int, sectionId: Int, progress: Int, studied: Bool) {
        if (sectionId == 0) {
            return
        }
        
        if (!DBUtils.mem.loginStatus || progress == 0) {
            return
        }
        
        let a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "lessonid": lessonId, "sectionid": sectionId, "progress": progress, "studied": studied]
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLSaveProgress(), parameters: (a as! [String : AnyObject]), responseHandler: nil, netErrorHandler: nil, successHandler: nil, interErrorHandler: nil, jsonErrorHandler: nil)
        
    }
    
    func playbackStateDidChange(notification: NSNotification) {
        var state = (notification.object as! MPMoviePlayerController).playbackState
        
        if (state == MPMoviePlaybackState.Interrupted) {
            self.indicatorView?.startAnimating()
        } else {
            self.indicatorView?.stopAnimating()
        }
    }
    
    func playerLoadStateDidChange(notification: NSNotification) {
        var moviePlayer = notification.object as! MPMoviePlayerController
        
        if (self.playStatus && (moviePlayer.loadState == MPMovieLoadState.Unknown || moviePlayer.loadState == MPMovieLoadState.Stalled)) {
            self.indicatorView?.startAnimating()
        } else {
            self.indicatorView?.stopAnimating()
        }
    }
    
    func playerPlayBackDidFinish(notification: NSNotification) {
        self.playStatus = false
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Normal)
        self.playButton1?.setBackgroundImage(self.playImg1, forState: UIControlState.Highlighted)
        self.isPlaybackFinished = true
    
        if (self.videoPlayer != nil && !isnan(self.videoPlayer!.currentPlaybackTime) && !isinf(self.videoPlayer!.currentPlaybackTime)) {
            let time = Int(self.videoPlayer!.currentPlaybackTime)
            self.nowTimeLabel1?.text = StringUtils.getFormatPlayTime(time)
            self.slider1?.setValue(Float(time), animated: true)
        }
        
    }
    
    func playerReadyForDisplayDidChange(notification: NSNotification) {
        if (self.videoPlayer!.readyForDisplay) {
            self.indicatorView?.stopAnimating()
            if (self.shouldSetProgress) {
                self.shouldSetProgress = false
                if (self.progress != 0) {
                    self.videoPlayer!.currentPlaybackTime = Double(self.progress)
                }
            }
        }
    }
    
    func applicationWillResignActive(notification: NSNotification) {
//        self.download?.stop()
//        self.isDownloading = false
        syncProgress()
    }
    
    func applicationDidBecomeActive(notification: NSNotification) {
        if (self.playStatus) {
            self.play()
        } else {
            self.pause()
        }
//        if (self.netStatus == Reachability.NetworkStatus.ReachableViaWiFi && self.vid != "") {
//            if (!self.download!.isVideoExists(self.vid, level: 1) && !self.isDownloading) {
//                download?.start(self.vid, level: 1)
//                self.isDownloading = true
//            }
//        }
    }
    
    // MARK: - 网络检测
    
    func reachabilityChanged(note: NSNotification) {
        
        let reachability = note.object as! Reachability
        
        self.netStatus = self.reachability?.currentReachabilityStatus
        
        if (self.netStatus == Reachability.NetworkStatus.ReachableViaWWAN) {
            if (self.playStatus && !self.allowCellular) {
                playButtonTapped()
                popPlayCheckView()
            }
//            self.download?.stop()
//            self.isDownloading = false
        } else if (self.netStatus == Reachability.NetworkStatus.ReachableViaWiFi && self.vid != "") {
//            if (!self.download!.isVideoExists(self.vid, level: 1) && !self.isDownloading) {
//                download?.start(self.vid, level: 1)
//                self.isDownloading = true
//            }
        } else if (self.netStatus == Reachability.NetworkStatus.NotReachable) {
//            self.download?.stop()
//            self.isDownloading = false
//            ViewUtils.popMessage(self, title: "", message: "网络连接异常")
        }
    }
    
    // MARK: - DownloadDelegate
    
    func downloadDidFinished(downloader: VideoDownloader!, withVid vid: String!) {
//        println("finished")
    }
    
    func dataDownloadAtPercent(downloader: VideoDownloader!, withVid vid: String!, percent aPercent: NSNumber!) {
//        println(aPercent.floatValue)
//        self.progressView?.setProgress(aPercent.floatValue / 100, animated: true)
    }
    
    func dataDownloadFailed(downloader: VideoDownloader!, withVid vid: String!, reason: String!) {
        
    }
    
    // MARK: - 实现sectionId传值协议
    
    func deliverSectionid(sectionId: Int, imgUrl: String) {
        syncProgress()
        
        self.sectionId = sectionId
        getVideoInfo(sectionId)
    }
    
    func playInFullScreen() {
        fullScreenButtonTapped()
    }
    
    func syncProgress() {
        if (self.videoPlayer != nil && !isnan(self.videoPlayer!.currentPlaybackTime) && !isinf(self.videoPlayer!.currentPlaybackTime)) {
            let time = Int(self.videoPlayer!.currentPlaybackTime)
            
            syncProgress(self.lessonId!, sectionId: self.sectionId, progress: time, studied: self.isPlaybackFinished)
        }
    }
    
    func setVideoImg(imgUrl: String) {
        self.isPosterImageview = true
        self.posterImageUrl = imgUrl
        DBUtils.getImageFromFile(self.posterImageUrl, successHandler: setFirstImage)
    }
    
    // MARK: - 网络调用
    
    func getVideoInfo(sectionId: Int) {
        let a = ["userid": String(DBUtils.mem.userId), "token": DBUtils.mem.token, "sectionid": String(sectionId)]
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLSectionVideo(), parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: setVideo, interErrorHandler: nil, jsonErrorHandler: nil)
    }
    
    func setVideo(json: JSON) {
        vid = json["vid"].string!
//        vid = "64770006a1ef3d2b23d9d23e2ba1d1	9d_6"
        self.progress = json["progress"].int!
        
        initVideo()
    }
        
    func isFree(freeType:Int)
    {
        self.isFree = freeType
    }
    // MARK: - Navigation
    /*
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
   
    @IBAction func learnButtonClick(sender: AnyObject) {
        if(DBUtils.mem.loginStatus)
        {
            if (DBUtils.mem.vipType == "NONE_VIP")//判断免费章节，转购买界面
            {
                if (self.isFree == 1)//如果不是vip，判断有无免费章节，
                {
                    fullScreenButtonTapped()
                }
                else
                {
                    var viewController = UIStoryboard(name: "Setting", bundle: nil).instantiateViewControllerWithIdentifier("Payment") as! PaymentViewController
                    rootController.navigationController?.pushViewController(viewController,animated:true)
                    self.navigationController?.setNavigationBarHidden(false, animated: true)

                }
            }
            else//直接播放
            {
                fullScreenButtonTapped()
            }
        }
        else
        {
            var viewController = UIStoryboard(name: "Login", bundle: nil).instantiateViewControllerWithIdentifier("Login") as! LoginViewController
            viewController.sourceNavi = false

            rootController.navigationController?.pushViewController(viewController,animated:true)
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            
        }
    
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        //  super.viewDidDisappear(animated)
        //  super.viewDidDisappear(animated)
        
    }

}
